//
// Created by YANHAI on 2020/4/20.
//

#include <iostream>
#include <fstream>
#include <boost/algorithm/hex.hpp>
#include <boost/uuid/detail/md5.hpp>

using namespace std;

bool GetMd5(std::string &str_md5, const char *const buffer, size_t buffer_size)
{
    if (buffer == nullptr) {
        return false;
    }
    boost::uuids::detail::md5 boost_md5;
    boost_md5.process_bytes(buffer, buffer_size);
    boost::uuids::detail::md5::digest_type digest;
    boost_md5.get_digest(digest);
    const auto char_digest = reinterpret_cast<const char *>(&digest);
    str_md5.clear();
    boost::algorithm::hex(char_digest, char_digest + sizeof(boost::uuids::detail::md5::digest_type),
                          std::back_inserter(str_md5));
    return true;
}

bool GetMd5(std::string &str_md5, const std::string &file)
{
    stringstream buffer;
    boost::uuids::detail::md5 boost_md5;
    ifstream fin(file);
    if (!fin) {
        return false;
    } else {
        buffer << fin.rdbuf();
        fin.close();
    }

    string data(buffer.str());

    cout << data << endl;
    cout << data.length() << endl;
    boost_md5.process_bytes(data.c_str(), data.length());
    boost::uuids::detail::md5::digest_type digest;
    boost_md5.get_digest(digest);
    const auto char_digest = reinterpret_cast<const char *>(&digest);
    str_md5.clear();
    boost::algorithm::hex(char_digest, char_digest + sizeof(boost::uuids::detail::md5::digest_type),
                          std::back_inserter(str_md5));
    transform(str_md5.begin(), str_md5.end(), str_md5.begin(), ::tolower);
    return true;
}

int main()
{
    std::string md5;
    GetMd5(md5, "hello", 5);
    std::cout << md5 << std::endl;
    GetMd5(md5, "/root/test.txt");
    std::cout << md5 << std::endl;
    typedef unsigned int(digest_type)[4];
    digest_type a;
    cout << sizeof(boost::uuids::detail::md5::digest_type) << endl;
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;

    int b[4];


    return 0;
}
